package models

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/go-redis/redis/v7"
	"github.com/sideshow/apns2"
	"github.com/sideshow/apns2/certificate"
	"github.com/sideshow/apns2/payload"
	"log"
	"strings"
	"time"
)

func pushMsg(msg, token string) {
	logs.Info("push token " + token)

	cert, err := certificate.FromP12File("models/cert.p12", "123456")
	if err != nil {
		log.Fatal("Cert Error:", err)
	}

	notification := &apns2.Notification{}

	notification.DeviceToken = token
	notification.Topic = "com.pluto.edith.Edith"
	notification.Payload = payload.NewPayload().Alert(msg).Sound("default")

	client := apns2.NewClient(cert).Development()
	client.Host = "https://api.development.push.apple.com"
	res, err := client.Push(notification)

	if err != nil {
		log.Fatal("Error:", err)
	}

	fmt.Printf("%v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}

func Push(msg string) {
	token := getRedisCon().Keys("token:*").Val()
	for i := 0; i < len(token); i++ {
		pushMsg(msg, strings.Split(token[i], ":")[1])
	}
}

func Register(token string) {
	token = strings.ReplaceAll(token, "\"", "")
	logs.Info("register token " + token)
	getRedisCon().Set("token:"+token, token, time.Hour*2400)
	getRedisCon().SAdd("device_token", token)
}

func getRedisCon() *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr:     "hx.anymre.top:8001",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	_, err := client.Ping().Result()
	if err != nil {
		logs.Info("cache init fail " + err.Error())
	}
	return client
}
